package com.gonsin.i18n.logic.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Aes {

    private Aes() {
    }

//	public static final String bytesPrint(byte[] in) {
//		StringBuilder sb = new StringBuilder();
//		for (int i = 0; i < in.length; i++) {
//			sb.append(in[i]).append(",");
//		}
//		String out = sb.toString();
//		System.out.println(out);
//		return out;
//	}

    public static final byte[] encBytes(byte[] srcBytes, byte[] key,
                                        byte[] newIv) throws Exception {
        Cipher cipher = Cipher.getInstance("Aes/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(key, "Aes");
        IvParameterSpec iv = new IvParameterSpec(newIv);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(srcBytes);
        return encrypted;
    }

    public static final String encText(String sSrc, byte[] key, byte[] newIv)
            throws Exception {
        byte[] srcBytes = sSrc.getBytes("utf-8");
        byte[] encrypted = encBytes(srcBytes, key, newIv);
        return Base64.encode(encrypted);
    }

    public static final byte[] decBytes(byte[] srcBytes, byte[] key,
                                        byte[] newIv) throws Exception {
        Cipher cipher = Cipher.getInstance("Aes/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(key, "Aes");
        IvParameterSpec iv = new IvParameterSpec(newIv);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(srcBytes);
        return encrypted;
    }

    public static final String decText(String sSrc, byte[] key, byte[] newIv)
            throws Exception {
        byte[] srcBytes = Base64.decode(sSrc);
        byte[] decrypted = decBytes(srcBytes, key, newIv);
        return new String(decrypted, "utf-8");
    }

}
